﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Magic.Core;

/// <summary>
/// 自定义HttpContext
/// </summary>
public static class App
{
    private static IHttpContextAccessor accessor;
    public static HttpContext HttpContext => accessor.HttpContext;
    public static IServiceProvider ServiceProvider { get; set; }

    internal static void SaveHttpContextAccessor(IHttpContextAccessor _accessor)
    {
        accessor = _accessor;
    }
}


public static class HttpContextAccessor_ApplicationBuilderExtensions
{
    /// <summary>
    /// 注册HttpContextAccessor
    /// </summary>
    /// <param name="services"></param>
    public static void AddAppHttpContextAccessor(this IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    public static IApplicationBuilder UseAppHttpContextAccessor(this IApplicationBuilder app)
    {
        var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
        App.SaveHttpContextAccessor(httpContextAccessor);
        App.ServiceProvider = app.ApplicationServices;
        return app;
    }
}
